function promisify(fn) {
  return async function(args) {
    return new Promise((resolve, reject) => {
      fn({...(args || {}),
        success: res => {
          resolve(res)
        },
        fail: err => {
          console.log('wx api failed');
          //console.log(err);
          reject(err)
        }
      });
    });
  };
}

function wxToAsync(names) {
  return (names || [])
    .map(name => (
      {
        name,
        member: wx[name]
      }
    ))
    .filter(t => typeof t.member === "function")
    .reduce((r, t) => {
      r[t.name] = promisify(wx[t.name]);
      return r;
    }, {});
}

function wxCloudToAsync(names) {
  return (names || [])
    .map(name => (
      {
        name,
        member: wx.cloud[name]
      }
    ))
    .filter(t => typeof t.member === "function")
    .reduce((r, t) => {
      r[t.name] = promisify(wx.cloud[t.name]);
      return r;
    }, {});
}

const awx = wxToAsync(["getSetting", "getUserInfo", "request"]);
awx.cloud = wxCloudToAsync(["callFunction"]);
module.exports=awx;